package com.jdz.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.jdz.common.Const;
import com.jdz.common.ServerResponse;
import com.jdz.dao.*;
import com.jdz.pojo.*;
import com.jdz.service.IProjectDetailsService;
import com.jdz.service.IRaceTypeService;
import com.jdz.util.DateTimeUtil;
import com.jdz.util.ExportExcel;
import com.jdz.vo.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by sun
 **/
@Transactional
@Service("IProjectDetailsService")
public class ProjectDetailsServiceImpl implements IProjectDetailsService {

    private Logger logger = LoggerFactory.getLogger(ProjectDetailsServiceImpl.class);

    @Autowired
    IRaceTypeService iRaceTypeService;
    @Autowired
    InstituteMapper instituteMapper;
    @Autowired
    ProjectDetailsMapper projectDetailsMapper;
    @Autowired
    ProjectDetailsUserMapper projectDetailsUserMapper;
    @Autowired
    GroupUserMapper groupUserMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ExcellentWorksMapper excellentWorksMapper;
    @Autowired
    RaceTypeMapper raceTypeMapper;
    @Autowired
    RaceTypeDetailsMapper raceTypeDetailsMapper;
    @Autowired
    ProjectDetailsRaceTypeSamsaraMapper projectDetailsRaceTypeSamsaraMapper;
    @Autowired
    RaceTypeSamsaraMapper raceTypeSamsaraMapper;
    @Autowired
    ScoreReviewMapper scoreReviewMapper;


    //portal

    @Override
    public ServerResponse saveOrUpdateProduct(ProjectDetails projectDetails, Integer stuno) {





        if(StringUtils.isBlank(projectDetails.getProjecttype())){
            return ServerResponse.createByErrorMessage("未选择项目类型");
        }
        if(StringUtils.isBlank(projectDetails.getProjectname())){
            return ServerResponse.createByErrorMessage("未输入项目名称");
        }
        if(StringUtils.isBlank(projectDetails.getcoverurl())){
            return ServerResponse.createByErrorMessage("未添加项目图片");
        }
        if(StringUtils.isBlank(projectDetails.getTeam())){
            return ServerResponse.createByErrorMessage("未输入团队名称");
        }
        if(StringUtils.isBlank(projectDetails.getAddprojectstuname())){
            return ServerResponse.createByErrorMessage("未输入参与学生");
        }
        if(StringUtils.isBlank(projectDetails.getInstructor())){
            return ServerResponse.createByErrorMessage("未输入指导老师名称");
        }

        RaceType r = raceTypeMapper.selectByRaceType(projectDetails.getProjecttype());
        if(r == null){
            return ServerResponse.createByErrorMessage("找到不项目类型");
        }

        RaceTypeDetails rd = raceTypeDetailsMapper.selectByRacetypeno(r.getRacetypeno());


        if(r.getStatus()==1){
            return ServerResponse.createByErrorMessage("申报关闭，无法申报和修改");
        }
        if(rd!=null){
            if(rd.getRacetypedetailsstate()!=null){
                if(rd.getRacetypedetailsstate()==-1){
                    return ServerResponse.createByErrorMessage("比赛已结束，无法申报");
                }
            }
        }

//        if(rd!=null){
//            if(rd.getRacetypedetailsstate()!=0){
//                if(projectDetails.getProjectno()==null){
//                    return ServerResponse.createByErrorMessage("比赛已开始，不可申报项目");
//                }else {
//                    return ServerResponse.createByErrorMessage("比赛已开始，不可修改项目");
//                }
//
//            }
//        }

        if(projectDetails != null)
        {

            if(projectDetails.getProjectno() != null){
                //如果Count为0则项目不是该用户的
                int Count = projectDetailsUserMapper.selectByProjectUser(stuno,projectDetails.getProjectno());
                //如果判断为普通用户，且不是该项目用户则修改不了
                GroupUser groupUser = groupUserMapper.selectByUserNokey(stuno);
                if(Count==0&&groupUser.getGroupno()== Const.Role.ROLE_CUSTOMER){
                    return ServerResponse.createByErrorMessage("你无权操作该项目");
                }
                ProjectDetails p = projectDetailsMapper.selectByPrimaryKey(projectDetails.getProjectno());
                if(p==null){
                    return ServerResponse.createByErrorMessage("该项目不存在");
                }
                //项目类型不同时需要判断项目开始没有
                if(projectDetails.getProjecttype()!=p.getProjecttype()){
                    RaceType r2 = raceTypeMapper.selectByRaceType(p.getProjecttype());
                    if(r2==null){
                        return ServerResponse.createByErrorMessage("找不到项目类型");
                    }
                    RaceTypeDetails rd2 = raceTypeDetailsMapper.selectByRacetypeno(r2.getRacetypeno());
                    if(rd2!=null||rd!=null){
                        if(rd.getRacetypedetailsstate()!=0||rd2.getRacetypedetailsstate()!=0){
                            return ServerResponse.createByErrorMessage("比赛已开始，无法修改比赛类型");
                        }
                    }
                }


                int rowCount = projectDetailsMapper.updateByPrimaryKeySelective(projectDetails);
                if(rowCount > 0){
                    return ServerResponse.createBySuccessMessage("更新项目成功");
                }
                return ServerResponse.createByErrorMessage("更新项目失败");
            }else{
                //防止比赛开始还能申报，只能修改
                if(rd!=null){
                    if(rd.getRacetypedetailsstate()!=null){
                        if(rd.getRacetypedetailsstate()!=0){
                            return ServerResponse.createByErrorMessage("比赛已开始，无法申报");
                        }
                    }
                }
                if (projectDetails.getProjectname()==null){
                    return ServerResponse.createByErrorMessage("请输入项目名字");
                }
                int Count = projectDetailsMapper.selectByProjectCount(projectDetails.getProjectname());

                if(Count > 0){
                    return ServerResponse.createByErrorMessage("该项目已存在，添加失败");
                }


                RaceType raceType = raceTypeMapper.selectByRaceType(projectDetails.getProjecttype());
                if(raceType==null){
                    return ServerResponse.createByErrorMessage("该比赛类型不存在");
                }
                if(raceType.getStatus()!=0){
                    return ServerResponse.createByErrorMessage("该比赛类型已关闭");
                }

                int rowCount = projectDetailsMapper.insertSelective(projectDetails);
                ProjectDetails projectDetails11= projectDetailsMapper.selectByProject(projectDetails.getProjectname());

                ProjectDetailsUser projectDetailsUser = new ProjectDetailsUser();

                projectDetailsUser.setStuno(stuno);

                projectDetailsUser.setProjectno(projectDetails11.getProjectno());

                projectDetailsUser.setCreattime(new Date());

                int rowCount1 = projectDetailsUserMapper.insertSelective(projectDetailsUser);

                if(rowCount > 0||rowCount1>0){
                    return ServerResponse.createBySuccessMessage("新增项目成功");
                }

                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

                return ServerResponse.createByErrorMessage("新增项目失败");
            }
        }
        return ServerResponse.createByErrorMessage("新增或更新项目参数不正确");
    }


    public ServerResponse listMyProduct(Integer stuno){
        List<ProjectDetailsUser> projectDetailsUsersList = projectDetailsUserMapper.selectListProjectUser(stuno);
        if(CollectionUtils.isEmpty(projectDetailsUsersList)){
            logger.info("未找到项目");
        }
        List<ListMyProjectDetallsVo> listMyProjectDetallsVos = Lists.newArrayList();
        for(ProjectDetailsUser projectDetailsUserItem : projectDetailsUsersList){
            ListMyProjectDetallsVo listMyProjectDetallsVo = new ListMyProjectDetallsVo();
            ProjectDetails p = projectDetailsMapper.selectByPrimaryKey(projectDetailsUserItem.getProjectno());
            if(p == null){
                continue;
            }
            listMyProjectDetallsVo = assembleUserListVo(p);
            listMyProjectDetallsVos.add(listMyProjectDetallsVo);
        }
        return ServerResponse.createBySuccess(listMyProjectDetallsVos);
    }

    private ListMyProjectDetallsVo assembleUserListVo(ProjectDetails projectDetails) {

        ListMyProjectDetallsVo listMyProjectDetallsVo = new ListMyProjectDetallsVo();
        listMyProjectDetallsVo.setProjectno(projectDetails.getProjectno());
        listMyProjectDetallsVo.setProjectname(projectDetails.getProjectname());
        listMyProjectDetallsVo.setCreattime(DateTimeUtil.dateToStr(projectDetails.getCreattime(),"yyyy-MM-dd HH:mm"));
        return listMyProjectDetallsVo;
    }

    public ServerResponse detailsProduct(Integer stuno, Integer projectno){

        if(projectno==null||projectno==0){
            return ServerResponse.createByErrorMessage("没有接收到项目id");
        }


        int Count = projectDetailsUserMapper.selectByProjectUser(stuno,projectno);
        GroupUser groupUser = groupUserMapper.selectByUserNokey(stuno);
        if(Count<=0&&groupUser.getGroupno()== Const.Role.ROLE_CUSTOMER){
            return ServerResponse.createByErrorMessage("你无权操作该项目");
        }

        ProjectDetails projectDetails = projectDetailsMapper.selectByPrimaryKey(projectno);

        if(projectDetails==null){
           return ServerResponse.createByErrorMessage("找不到当前项目");
        }
        return  ServerResponse.createBySuccess(projectDetails);
    }



    public ServerResponse excellentWorksDetailsProduct(Integer projectno){

        if(projectno==null||projectno==0){
            return ServerResponse.createByErrorMessage("没有接收到项目id");
        }

        ExcellentWorks excellentWorks = excellentWorksMapper.selectByProjectNo(projectno);
        if(excellentWorks!=null){
            ProjectDetails projectDetails = projectDetailsMapper.selectByPrimaryKey(projectno);

            if(projectDetails==null){
                return ServerResponse.createByErrorMessage("找不到当前项目");
            }
            return  ServerResponse.createBySuccess(projectDetails);
        }
        return ServerResponse.createByErrorMessage("不是优秀项目");
    }

    //backend

    public ServerResponse detailsProductAdmin(HttpSession session,Integer projectno){

        if(projectno==null||projectno==0){
            return ServerResponse.createByErrorMessage("没有接收到项目id");
        }

        UserVo userVo = (UserVo) session.getAttribute(Const.CURRENT_USER);


        ProjectDetails projectDetails = projectDetailsMapper.selectByPrimaryKey(projectno);

        if(projectDetails==null){
            return ServerResponse.createByErrorMessage("找不到当前项目");
        }

        RaceType raceType = raceTypeMapper.selectByRaceType(projectDetails.getProjecttype());

        if(raceType==null){
            return ServerResponse.createByErrorMessage("类型不存在");
        }
        RaceTypeDetails raceTypeDetails = raceTypeDetailsMapper.selectByRacetypeno(raceType.getRacetypeno());



        if(raceTypeDetails==null){
            projectDetails.setExaminestatus(0);
            projectDetails.setReviewnotes(null);
            projectDetails.setExamineresult(null);

            return  ServerResponse.createBySuccess(projectDetails);
        }else if(raceTypeDetails.getRacetypedetailsstate()==0){
            System.out.println("2");
            projectDetails.setExaminestatus(0);
            projectDetails.setReviewnotes(null);
            projectDetails.setExamineresult(null);

            System.out.println("2");
            return  ServerResponse.createBySuccess(projectDetails);
        }else if(raceTypeDetails.getRacetypedetailsstate()==-1){
            int i = raceTypeSamsaraMapper.selectByRacetypeno(raceType.getRacetypeno()).size();
            if(i==0){
                return ServerResponse.createByErrorMessage("没有设置轮次");
            }else {
                RaceTypeSamsara raceTypeSamsaraif = raceTypeSamsaraMapper.selectByRacetypeno(raceType.getRacetypeno()).get(i-1);
                ProjectDetailsRaceTypeSamsara pp = projectDetailsRaceTypeSamsaraMapper.selectByprojectDetailsNoAndRacetypesamsarano(projectno,raceTypeSamsaraif.getRacetypesamsarano());
                if(pp==null){
                    System.out.println("5");
                    projectDetails.setExaminestatus(0);
                    projectDetails.setReviewnotes(null);
                    projectDetails.setExamineresult(null);

                    return  ServerResponse.createBySuccess(projectDetails);//shuchu
                }else {
                    System.out.println("6");
                    projectDetails.setExaminestatus(pp.getExaminestatus());

                    ScoreReview scoreReview = scoreReviewMapper.selectByProjracenoAndStuno(pp.getProjraceno(),userVo.getStuno());
                    projectDetails.setReviewnotes(String.valueOf(scoreReview.getReviewnotes()));
                    projectDetails.setExamineresult(scoreReview.getResult());


                    return  ServerResponse.createBySuccess(projectDetails);
                }
            }
        }else {
            System.out.println("3");
            RaceTypeSamsara raceTypeSamsara = raceTypeSamsaraMapper.selectByRacetypenoAndRaceTypeSamsaraGrade(raceType.getRacetypeno(),raceTypeDetails.getRacetypedetailsstate());

            if(raceTypeSamsara==null){

                return ServerResponse.createByErrorMessage("当前轮次不存在");
            }else {
                ProjectDetailsRaceTypeSamsara p = projectDetailsRaceTypeSamsaraMapper.selectByprojectDetailsNoAndRacetypesamsarano(projectno,raceTypeSamsara.getRacetypesamsarano());
                System.out.println("==========="+projectno+"=="+raceTypeSamsara.getRacetypesamsarano());
                if(p==null){

                    projectDetails.setExaminestatus(0);
                    projectDetails.setReviewnotes(null);
                    projectDetails.setExamineresult(null);


                    return  ServerResponse.createBySuccess(projectDetails);//shuchu
                }else {

                    ScoreReview scoreReview = scoreReviewMapper.selectByProjracenoAndStuno(p.getProjraceno(),userVo.getStuno());
                    projectDetails.setReviewnotes(String.valueOf(scoreReview.getReviewnotes()));
                    projectDetails.setExamineresult(scoreReview.getResult());

                    return  ServerResponse.createBySuccess(projectDetails);
                }


            }


        }



    }

    /**
     * 管理员首页
     * @return
     */
    public ServerResponse IndexCount(){
        Map<String,Object> map = new HashMap<>();


        List<RaceTypeVo> raceTypeList = iRaceTypeService.getParallelRaceType(0).getData();

        Integer aggregatestunamenumNull=0;
        Integer aggregateexamineNo=0;

        for(RaceTypeVo item:raceTypeList){
            List<RaceTypeVo> raceTypeVoList = iRaceTypeService.getParallelRaceType(item.getRacetypeno()).getData();
            //下面循环的是每个比赛
            for(RaceTypeVo item2:raceTypeList){
                RaceTypeDetails raceTypeDetails = raceTypeDetailsMapper.selectByRacetypeno(item2.getRacetypeno());
                if(raceTypeDetails==null){
                    continue;
                }
                if (raceTypeDetails.getRacetypedetailsstate()==0||raceTypeDetails.getRacetypedetailsstate()==-1){
                    continue;
                }
                RaceTypeSamsara raceTypeSamsara = raceTypeSamsaraMapper.selectByRacetypenoAndRaceTypeSamsaraGrade(item2.getRacetypeno(),raceTypeDetails.getRacetypedetailsstate());
                if(raceTypeSamsara==null){
                    continue;
                }
                List<ProjectDetailsRaceTypeSamsara> projectDetailsRaceTypeSamsaraList = projectDetailsRaceTypeSamsaraMapper.selectByRacetypesamsarano(raceTypeSamsara.getRacetypesamsarano());
                for(ProjectDetailsRaceTypeSamsara item3:projectDetailsRaceTypeSamsaraList){
                    if(item3.getExaminestatus()==0){
                        aggregateexamineNo+=1;
                    }
                }
            }
        }
        List<ProjectDetails> projectDetailsList = projectDetailsMapper.selectByProjectAll();

        for(ProjectDetails item:projectDetailsList){
            int i = excellentWorksMapper.selectByProjectNoCount(item.getProjectno());
            if(i>0){
                aggregatestunamenumNull+=1;
            }
        }

        map.put("总用户数",userMapper.selectListUserCount());
        map.put("总项目数",projectDetailsMapper.selectByProjectAll().size());
//        map.put("优秀项目数",excellentWorksMapper.seletAll().size());

        map.put("优秀项目数",aggregatestunamenumNull);
        map.put("未审核总项目数",aggregateexamineNo);

        return ServerResponse.createBySuccess(map);
    }


    /**
     * 项目分类统计
     * @return
     */
    public ServerResponse raceTypeProjectDetailsCount(){
//        List<RaceTypeVo> raceTypeList = iRaceTypeService.getParallelRaceType(0).getData();
//
//        Set<RaceTypeProjectDetailsCountVo> setNum = Sets.newHashSet();
//
//        int aggregatenum=0;//总人数
//        double aggregatereviewnotes=0;//总平均分
//        int aggregatestunamenumNull = 0;//没录分总人数
//        int aggregateexamineNo = 0;  //未审核总人数
//        for(RaceTypeVo raceTypeItem : raceTypeList){
//            List<RaceTypeVo> raceTypeList1 = iRaceTypeService.getParallelRaceType(raceTypeItem.getRacetypeno()).getData();
//            for (RaceTypeVo raceTypeItem1 : raceTypeList1){
//                List<ProjectDetails> projectDetailsList = projectDetailsMapper.selectByProjectRaceType(raceTypeItem1.getRacetype());
//                double reviewnotes = 0;  //平均分数
//                int  stunamenum = 0;   //每个类型的人数
//                int stunamenumNull = 0; //没录分人数
//                int examineNo = 0;  //未审核人数
//                for(ProjectDetails projectDetailsItem : projectDetailsList){
//
////                    if(projectDetailsItem.getExaminestatus()==1&&projectDetailsItem.getReviewnotes()!=null) {
////                        reviewnotes += Double.parseDouble(projectDetailsItem.getReviewnotes());
////                    }
////
//                    stunamenum += projectDetailsItem.getAddprojectstuname().split(",|，").length;
////
////                    if(projectDetailsItem.getReviewnotes()==null){
////                        stunamenumNull += projectDetailsItem.getAddprojectstuname().split(",|，").length;
////                    }else if(projectDetailsItem.getExaminestatus()==0||projectDetailsItem.getExaminestatus()==1){
////                        examineNo += projectDetailsItem.getAddprojectstuname().split(",|，").length;
////                    }
//                    List<ProjectDetailsRaceTypeSamsara> projectDetailsRaceTypeSamsaraList =  projectDetailsRaceTypeSamsaraMapper.selectByprojectDetailsNo(projectDetailsItem.getProjectno());
//
//                    int i = 0;
//                    double reviewnote = 0;
//                    for(ProjectDetailsRaceTypeSamsara projectDetailsRaceTypeSamsaraItem : projectDetailsRaceTypeSamsaraList){
//                        if(projectDetailsRaceTypeSamsaraItem.getReviewnotes()!=null){
//                            i++;
//                            reviewnote+=Double.parseDouble(projectDetailsRaceTypeSamsaraItem.getReviewnotes());
//                        }
//                    }
//                    if(i!=0){
//                        reviewnotes+=reviewnote/i;
//                    }
//
//
//
//                    RaceTypeDetails raceTypeDetails = raceTypeDetailsMapper.selectByRacetypeno(raceTypeItem1.getRacetypeno());
//                    if(raceTypeDetails==null||raceTypeDetails.getRacetypedetailsstate()==0){
//                        stunamenumNull += projectDetailsItem.getAddprojectstuname().split(",|，").length;
//                        examineNo += projectDetailsItem.getAddprojectstuname().split(",|，").length;
//                    }else if(raceTypeDetails.getRacetypedetailsstate()==-1){
//                        //如果项目结束，最后一轮评审才算
//                        if(projectDetailsRaceTypeSamsaraList.size()==raceTypeDetails.getRacetypedetailsstate()){
//                            ProjectDetailsRaceTypeSamsara projectDetailsRaceTypeSamsara_if = projectDetailsRaceTypeSamsaraList.get(-1);
//                            if(projectDetailsRaceTypeSamsara_if.getReviewnotes()==null){
//                                stunamenumNull += projectDetailsItem.getAddprojectstuname().split(",|，").length;
//                            }
//                            if(projectDetailsRaceTypeSamsara_if.getExaminestatus()!=0){
//                                examineNo += projectDetailsItem.getAddprojectstuname().split(",|，").length;
//                            }
//                        }else {
//                            stunamenumNull += projectDetailsItem.getAddprojectstuname().split(",|，").length;
//                            examineNo += projectDetailsItem.getAddprojectstuname().split(",|，").length;
//                        }
//                    }else {
//                        ProjectDetailsRaceTypeSamsara projectDetailsRaceTypeSamsara_el = projectDetailsRaceTypeSamsaraList.get(raceTypeDetails.getRacetypedetailsstate()-1);
//                        if(projectDetailsRaceTypeSamsara_el.getReviewnotes()==null){
//                            stunamenumNull += projectDetailsItem.getAddprojectstuname().split(",|，").length;
//                        }
//                        if(projectDetailsRaceTypeSamsara_el.getExaminestatus()!=0){
//                            examineNo += projectDetailsItem.getAddprojectstuname().split(",|，").length;
//                        }
//                    }
//
//                }
//                aggregatenum+=stunamenum;
//                aggregatereviewnotes+=reviewnotes;
//                aggregateexamineNo+=examineNo;
//                aggregatestunamenumNull+=stunamenumNull;
//
//                RaceTypeProjectDetailsCountVo raceTypeProjectDetailsCountVo = new RaceTypeProjectDetailsCountVo();
//                raceTypeProjectDetailsCountVo.setNum(stunamenum);
//                raceTypeProjectDetailsCountVo.setAverage(reviewnotes/projectDetailsList.size());
//                raceTypeProjectDetailsCountVo.setRateTypename(raceTypeItem1.getRacetype());
//                setNum.add(raceTypeProjectDetailsCountVo);
//            }
//
//        }
//        RaceTypeProjectDetailsAggregateVo raceTypeProjectDetailsAggregateVo = new RaceTypeProjectDetailsAggregateVo();
//        raceTypeProjectDetailsAggregateVo.setAggregatenum(aggregatenum);
//        raceTypeProjectDetailsAggregateVo.setAggregateaverage(aggregatereviewnotes/(aggregatenum-aggregateexamineNo-aggregatestunamenumNull));
//        raceTypeProjectDetailsAggregateVo.setRaceTypeProjectDetailsCountVoSet(setNum);
//
//        return ServerResponse.createBySuccess("项目分类统计完成",raceTypeProjectDetailsAggregateVo);
        List<RaceTypeVo> raceTypeList = iRaceTypeService.getParallelRaceType(0).getData();

        List<RaceTypeProjectDetailsCountVo> setNum = new ArrayList<>();

        int aggregatenum=0;//总人数
        double aggregatereviewnotes=0;//总平均分
        int xiangmunums =0; //总有效项目数
        for(RaceTypeVo raceTypeItem : raceTypeList){
            List<RaceTypeVo> raceTypeList1 = iRaceTypeService.getParallelRaceType(raceTypeItem.getRacetypeno()).getData();
            for (RaceTypeVo raceTypeItem1 : raceTypeList1){
                List<ProjectDetails> projectDetailsList = projectDetailsMapper.selectByProjectRaceType(raceTypeItem1.getRacetype());
                double reviewnotes = 0;  //平均分数
                int  stunamenum = 0;   //每个类型的人数
                int xiangmunum =0; //有效项目数

                for(ProjectDetails projectDetailsItem : projectDetailsList){


                    stunamenum += projectDetailsItem.getAddprojectstuname().split(",|，").length;

                    List<ProjectDetailsRaceTypeSamsara> projectDetailsRaceTypeSamsaraList =  projectDetailsRaceTypeSamsaraMapper.selectByprojectDetailsNo(projectDetailsItem.getProjectno());

                    int i = 0;
                    double reviewnote = 0;
                    for(ProjectDetailsRaceTypeSamsara projectDetailsRaceTypeSamsaraItem : projectDetailsRaceTypeSamsaraList){
                        if(projectDetailsRaceTypeSamsaraItem.getReviewnotes()!=null){
                            i++;
                            reviewnote+=Double.parseDouble(projectDetailsRaceTypeSamsaraItem.getReviewnotes());
                        }
                    }
                    if(i!=0){
                        xiangmunum++;
                        reviewnotes+=reviewnote/i;
                    }

                }
                aggregatenum+=stunamenum;
                aggregatereviewnotes+=reviewnotes;
                xiangmunums+=xiangmunum;


                RaceTypeProjectDetailsCountVo raceTypeProjectDetailsCountVo = new RaceTypeProjectDetailsCountVo();
                raceTypeProjectDetailsCountVo.setNum(stunamenum);
                if(xiangmunums!=0){
                    raceTypeProjectDetailsCountVo.setAverage(reviewnotes/xiangmunum);
                }else {
                    raceTypeProjectDetailsCountVo.setAverage(0);
                }
                raceTypeProjectDetailsCountVo.setRateTypename(raceTypeItem1.getRacetype());
                setNum.add(raceTypeProjectDetailsCountVo);
            }

        }
        RaceTypeProjectDetailsAggregateVo raceTypeProjectDetailsAggregateVo = new RaceTypeProjectDetailsAggregateVo();
        raceTypeProjectDetailsAggregateVo.setAggregatenum(aggregatenum);
        raceTypeProjectDetailsAggregateVo.setAggregateaverage(new BigDecimal(aggregatereviewnotes/xiangmunums).setScale(2, RoundingMode.UP).doubleValue());
        raceTypeProjectDetailsAggregateVo.setRaceTypeProjectDetailsCountVoSet(setNum);

        return ServerResponse.createBySuccess("项目分类统计完成",raceTypeProjectDetailsAggregateVo);
    }


    /**
     * 院级分类统计
     * @param raceTypename
     * @return
     */
    public ServerResponse InstitutionCount(String  raceTypename){

        List<Institute> instituteList = instituteMapper.selectList();

        int numAggregate = 0;
        double stuaverageAggregate = 0;
        int aggregatestunamenumNull = 0;//没录总分人数

        Set<InstituteProjectDetailsVo> instituteProjectDetailsVoSet = Sets.newHashSet();




            for(Institute instituteItem : instituteList){

                int num = 0;
                double stuaverage = 0;
                int stunamenumNull = 0; //没录分人数

                if(StringUtils.equals(raceTypename,"all")) {
                    instituteItem.setStuinstitutename("null");
                }

                List<User> userList = userMapper.selectInstituteUser(instituteItem.getStuinstitutename(),null,null);
                List<Integer> stunoList = Lists.newArrayList();
                for(User userItem : userList){
                    stunoList.add(userItem.getStuno());
                }
                List<ProjectDetailsUser> projectDetailsUserList = projectDetailsUserMapper.selecttProjectstunoList(stunoList);

                List<Integer> projectDetailsnoList = Lists.newArrayList();
                List<Integer> projectDetailsnoListNoCredit = Lists.newArrayList();
                for(ProjectDetailsUser projectDetailsUserItem : projectDetailsUserList){

                    if(projectDetailsUserItem.getCredit()!=null){
                        stuaverage += Double.parseDouble(projectDetailsUserItem.getCredit());
                        stuaverageAggregate += Double.parseDouble(projectDetailsUserItem.getCredit());
                    }
                    if(projectDetailsUserItem.getCredit()==null){
                        projectDetailsnoListNoCredit.add(projectDetailsUserItem.getProjectno());
                    }

                    projectDetailsnoList.add(projectDetailsUserItem.getProjectno());
                }
                List<ProjectDetails> projectDetailsList = projectDetailsMapper.selectByProjectnoList(projectDetailsnoList);
                List<ProjectDetails> projectDetailsListNoCredit = projectDetailsMapper.selectByProjectnoList(projectDetailsnoListNoCredit);

                for(ProjectDetails projectDetailsItem : projectDetailsList){
                    num += projectDetailsItem.getAddprojectstuname().split(",|，").length;
                    numAggregate += projectDetailsItem.getAddprojectstuname().split(",|，").length;
                }
                for(ProjectDetails projectDetailsItem : projectDetailsListNoCredit){
                    stunamenumNull += projectDetailsItem.getAddprojectstuname().split(",|，").length;
                    aggregatestunamenumNull += projectDetailsItem.getAddprojectstuname().split(",|，").length;
                }

                InstituteProjectDetailsVo instituteProjectDetailsVo = new InstituteProjectDetailsVo();
                instituteProjectDetailsVo.setNum(num);
                instituteProjectDetailsVo.setStuaverage(stuaverage/(num-stunamenumNull));
                instituteProjectDetailsVoSet.add(instituteProjectDetailsVo);
            }

        InstituteAggregateProjectDetailsVo instituteAggregateProjectDetailsVo = new InstituteAggregateProjectDetailsVo();
        instituteAggregateProjectDetailsVo.setNumAggregate(numAggregate);
        instituteAggregateProjectDetailsVo.setStuaverageAggregate(stuaverageAggregate/(numAggregate-aggregatestunamenumNull));
        instituteAggregateProjectDetailsVo.setInstituteProjectDetailsVoSet(instituteProjectDetailsVoSet);
        return ServerResponse.createBySuccess("院级分类统计成功",instituteAggregateProjectDetailsVo);
    }



    /**
     * 项目评审
     * @param stuname 评审人名称
     * @param reviewnotes 评审分数
     * @return
     */
    public ServerResponse Review(List<Integer> projectnoList, String stuname, double reviewnotes){

        String reviewnotestoString = String.valueOf(reviewnotes);

        if(CollectionUtils.isEmpty(projectnoList)){
            return ServerResponse.createByErrorMessage("未选择项目");
        }

        if(StringUtils.isBlank(stuname)){
            return ServerResponse.createByErrorMessage("评审批人不能为空");
        }
        if(StringUtils.isBlank(reviewnotestoString)){
            return ServerResponse.createByErrorMessage("分数不能为空");
        }

        for(Integer projectnoItem : projectnoList){
            ProjectDetails projectDetailsReturn = projectDetailsMapper.selectByPrimaryKey(projectnoItem);
            if(projectDetailsReturn.getExaminestatus()!=0){
                return ServerResponse.createByErrorMessage("选择项目中有已审核，不能再评审");
            }

            ProjectDetails projectDetails = new ProjectDetails();
            projectDetails.setReviewuser(stuname);
            projectDetails.setProjectno(projectnoItem);
            projectDetails.setReviewnotes(reviewnotestoString);
            projectDetails.setReviewtime(new Date());

            int rowCount1 = projectDetailsMapper.updateByPrimaryKeySelective(projectDetails);
            if(rowCount1 <= 0){
                return ServerResponse.createByErrorMessage("项目评审失败");
            }
        }

        return ServerResponse.createBySuccessMessage("项目评审成功");
    }

    /**
     * 项目审批
     * @param stuname
     * @param examinestatus
     * @param examineresult
     * @return
     */
    public ServerResponse Examine(List<Integer> projectnoList, String stuname, int examinestatus, String examineresult){
        if(CollectionUtils.isEmpty(projectnoList)){
            return ServerResponse.createByErrorMessage("未选择项目");
        }
        if(StringUtils.isBlank(stuname)){
            return ServerResponse.createByErrorMessage("审批人不能为空");
        }
        if(!(examinestatus==1||examinestatus==2)){
            return ServerResponse.createByErrorMessage("审批状态的参数不对");
        }

        for(Integer projectnoItem : projectnoList) {
            ProjectDetails projectDetailsReturn = projectDetailsMapper.selectByPrimaryKey(projectnoItem);
//            if(StringUtils.isBlank(projectDetailsReturn.getReviewnotes())){
//                return ServerResponse.createByErrorMessage("选择项目中有未评审，不能审核");
//            }
            if(projectDetailsReturn.getExaminestatus()!=0){
                return ServerResponse.createByErrorMessage("选择项目中有已审核，不能再审核");
            }


            ProjectDetails projectDetails = new ProjectDetails();
            projectDetails.setProjectno(projectnoItem);
            projectDetails.setExamineuser(stuname);
            projectDetails.setExaminestatus(examinestatus);
            projectDetails.setExamineresult(examineresult);
            projectDetails.setExaminetime(new Date());



            int rowCount1 = projectDetailsMapper.updateByPrimaryKeySelective(projectDetails);
            if(rowCount1 <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ServerResponse.createByErrorMessage("项目审批失败");
            }
        }
        return ServerResponse.createBySuccessMessage("项目审批成功");
    }


    /**
     * 项目列表
     * @param pageNum
     * @param pageSize
     * @param name
     * @param startTime
     * @param stopTime
     * @param projectType
     * @param stuInstitute
     * @param examineStatus
     * @return
     */
    public ServerResponse listProduct(int pageNum, int pageSize, String name, String startTime, String stopTime, String projectType, String stuInstitute, Integer examineStatus, int time_sort){



        Date startTimeDate;
        Date stopTimeDate;

        int  int_name;

        if(StringUtils.isBlank(name)){
            name=null;
        }
        if(StringUtils.isBlank(stuInstitute)){
            stuInstitute=null;
        }
        if(StringUtils.isBlank(projectType)){
            projectType = null;
        }


        try {
            int_name = Integer.parseInt(name);
        }catch (Exception e){
            int_name = 0;
        }




        try {



            if(StringUtils.isBlank(startTime))
                startTimeDate=null;
            else
                startTimeDate = DateTimeUtil.dateMin(startTime);

            if(StringUtils.isBlank(name))
                name=null;
            else
                name = new StringBuilder().append("%").append(name).append("%").toString();

            if(StringUtils.isBlank(stopTime))
                stopTimeDate=null;
            else
                stopTimeDate = DateTimeUtil.dateMin(stopTime);


        }catch (Exception e){
            return ServerResponse.createByErrorMessage("列出公告列表参数格式错误");
        }



        if(StringUtils.isBlank(stuInstitute)){



            List<ProjectDetails> projectDetailsList = projectDetailsMapper.selectByProjectListManage(int_name, projectType, name, startTimeDate, stopTimeDate);


            if(CollectionUtils.isEmpty(projectDetailsList)){
                return ServerResponse.createByErrorMessage("项目为空");
            }


            List<ListProjectDetailsVo> listProjectDetailsVos2 =  assembleProjectDetailsListVo(projectDetailsList);
            List<ListProjectDetailsVo> listProjectDetailsVos = new ArrayList<>();
            //筛选项目审核状态
            if(examineStatus!=null){
                for(ListProjectDetailsVo item:listProjectDetailsVos2){
                    if(item.getExaminestatus()==examineStatus){
                        listProjectDetailsVos.add(item);
                    }
                }
            }else {
                listProjectDetailsVos=listProjectDetailsVos2;
            }


            Map<String,Object> map = new HashMap<>();

            int pages = (int)(listProjectDetailsVos.size()/pageSize);
            if(listProjectDetailsVos.size()%pageSize!=0){
                pages+=1;
            }
            if(pageNum>pages){
                return ServerResponse.createBySuccessMessage("项目为空");
            }


            if(listProjectDetailsVos.size()%pageSize!=0){
                if(pages==pageNum){
                    map.put("list",listProjectDetailsVos.subList((pageNum-1)*pageSize,listProjectDetailsVos.size()));
                }else {
                    map.put("list",listProjectDetailsVos.subList((pageNum-1)*pageSize,pageNum*pageSize));
                }
            } else {
                map.put("list",listProjectDetailsVos.subList((pageNum-1)*pageSize,pageNum*pageSize));
            }
            map.put("pages",pages);
            map.put("pageNum",pageNum);
            map.put("pageSize",pageSize);
            map.put("pageTotal",listProjectDetailsVos.size());

            return ServerResponse.createBySuccess("返回项目列表成功",map);
        }else {

            List<Integer> selectInstitutelist = userMapper.selectInstitute(stuInstitute);

            if(CollectionUtils.isEmpty(selectInstitutelist)){
                return ServerResponse.createByErrorMessage("该学院还没有注册用户");
            }

            List<ProjectDetailsUser> projectDetailsUserList = projectDetailsUserMapper.selecttProjectstunoList(selectInstitutelist);

//            PageHelper.startPage(pageNum,pageSize);

            List<ProjectDetails> projectDetailsList = projectDetailsMapper.selectByProjectListManage(int_name,projectType,name,startTimeDate,stopTimeDate);

            if(CollectionUtils.isEmpty(projectDetailsList)){
                return ServerResponse.createByErrorMessage("项目为空");
            }


            List<ProjectDetails> rutlh = useLoop(projectDetailsList,projectDetailsUserList);

            if(CollectionUtils.isEmpty(rutlh)||CollectionUtils.isEmpty(projectDetailsUserList)){
                return ServerResponse.createByErrorMessage("项目为空");
            }

            List<ListProjectDetailsVo> listProjectDetailsVos2 =  assembleProjectDetailsListVo(rutlh);
            List<ListProjectDetailsVo> listProjectDetailsVos = new ArrayList<>();

            if(CollectionUtils.isEmpty(listProjectDetailsVos2)){
                return ServerResponse.createBySuccessMessage("项目为空");
            }


            //筛选项目审核状态
            if(examineStatus!=null){
                for(ListProjectDetailsVo item:listProjectDetailsVos2){
                    if(item.getExaminestatus()==examineStatus){
                        listProjectDetailsVos.add(item);
                    }
                }
            }else {
                listProjectDetailsVos=listProjectDetailsVos2;
            }
//
//            PageInfo pageResult = new PageInfo(projectDetailsList);
//            pageResult.setList(listProjectDetailsVos);

            Map<String,Object> map = new HashMap<>();

            int pages = (int)(listProjectDetailsVos.size()/pageSize);
            if(listProjectDetailsVos.size()%pageSize!=0){
                pages+=1;
            }
            if(pageNum>pages){
                return ServerResponse.createBySuccessMessage("项目为空");
            }


            if(listProjectDetailsVos.size()%pageSize!=0){
                if(pages==pageNum){
                    map.put("list",listProjectDetailsVos.subList((pageNum-1)*pageSize,listProjectDetailsVos.size()));
                }else {
                    map.put("list",listProjectDetailsVos.subList((pageNum-1)*pageSize,pageNum*pageSize));
                }
            } else {
                map.put("list",listProjectDetailsVos.subList((pageNum-1)*pageSize,pageNum*pageSize));
            }
            map.put("pages",pages);
            map.put("pageNum",pageNum);
            map.put("pageSize",pageSize);
            map.put("pageTotal",listProjectDetailsVos.size());

//            int [] data = {1,2,3,4,5,6,7,8,9};
//            int [] newData;
//            newData = Arrays.copyOfRange(data, 2, 7);
//
//            int pages = data.length/5;
//
//
//            newData = Arrays.copyOfRange(data, data.length-1, data.length);
//
//            for(int i:newData)
//                System.out.print(i+" ");
//        }


            return ServerResponse.createBySuccess("返回项目列表成功",map);
        }
    }

    public List<ListProjectDetailsVo> assembleProjectDetailsListVo(List<ProjectDetails> projectDetailsList){

        List<ListProjectDetailsVo> listProjectDetailsVos = Lists.newArrayList();



        for(ProjectDetails projectDetailsItem : projectDetailsList){


            ListProjectDetailsVo listProjectDetailsVo = new ListProjectDetailsVo();
            listProjectDetailsVo.setProjectno(projectDetailsItem.getProjectno());
            listProjectDetailsVo.setProjectname(projectDetailsItem.getProjectname());
            listProjectDetailsVo.setProjectgrade(projectDetailsItem.getProjectgrade());

            listProjectDetailsVo.setIsvaild(projectDetailsItem.getIsvaild());

            listProjectDetailsVo.setProjecttype(projectDetailsItem.getProjecttype());
            listProjectDetailsVo.setCreattime(DateTimeUtil.dateToStr(projectDetailsItem.getCreattime()));

            listProjectDetailsVo.setInstructor(projectDetailsItem.getInstructor());

            ProjectDetailsUser projectDetailsUser = projectDetailsUserMapper.selectByProjectno(projectDetailsItem.getProjectno());

            if(projectDetailsUser==null){
                continue;
            }

            User user = userMapper.selectByPrimaryKey(projectDetailsUser.getStuno());

            listProjectDetailsVo.setStuinstitute(user.getStuinstitute());
            listProjectDetailsVo.setUsername(user.getStuname());

            System.out.println(user.getStuinstitute()+"====="+user.getStuno());

            ExcellentWorks excellentWorks = excellentWorksMapper.selectByProjectNo(projectDetailsItem.getProjectno());
            if(excellentWorks==null){
                listProjectDetailsVo.setYouxiu_status(0);
            }else {
                if(excellentWorks.getStatus()==0){
                    listProjectDetailsVo.setYouxiu_status(1);
                }else {
                    listProjectDetailsVo.setYouxiu_status(0);
                }
            }

            RaceType raceType = raceTypeMapper.selectByRaceType(projectDetailsItem.getProjecttype());
            if(raceType==null){

//                listProjectDetailsVos.add(listProjectDetailsVo);
                continue;
            }
            RaceTypeDetails raceTypeDetails = raceTypeDetailsMapper.selectByRacetypeno(raceType.getRacetypeno());

            if(raceTypeDetails==null||raceTypeDetails.getRacetypedetailsstate()==null||raceTypeDetails.getRacetypedetailsstate()==0){
                listProjectDetailsVo.setRacetypedetailsstate(0);
                listProjectDetailsVo.setExaminestatus(0);
            }else {

                RaceTypeSamsara raceTypeSamsara = raceTypeSamsaraMapper.selectByRacetypenoAndRaceTypeSamsaraGrade(raceType.getRacetypeno(),raceTypeDetails.getRacetypedetailsstate());

                if(raceTypeSamsara==null){
                    listProjectDetailsVo.setExaminestatus(0);

                }else {
                    ProjectDetailsRaceTypeSamsara p = projectDetailsRaceTypeSamsaraMapper.selectByprojectDetailsNoAndRacetypesamsarano(projectDetailsItem.getProjectno(),raceTypeSamsara.getRacetypesamsarano());

                    if(p==null){
                        listProjectDetailsVo.setExaminestatus(0);
                    }else {
                        if(p.getExaminestatus()==null){
                            listProjectDetailsVo.setExaminestatus(0);
                        }else{
                            listProjectDetailsVo.setExaminestatus(p.getExaminestatus());
                        }

                    }
                }



                listProjectDetailsVo.setRacetypedetailsstate(raceTypeDetails.getRacetypedetailsstate());
            }
            //结束比赛了的话
            if(listProjectDetailsVo.getRacetypedetailsstate()==-1){
                int rr = raceTypeSamsaraMapper.selectByRacetypeno(raceType.getRacetypeno()).size();
                int iff = 0;
                //判断前面是否及格，是否要显示
                for(int i=1;i<=rr;i++){
                    RaceTypeSamsara raceTypeSamsaraIf = raceTypeSamsaraMapper.selectByRacetypenoAndRaceTypeSamsaraGrade(raceType.getRacetypeno(),i);
                    if(raceTypeSamsaraIf==null){
                        iff=1;
                        break;
                    }
                    ProjectDetailsRaceTypeSamsara pif = projectDetailsRaceTypeSamsaraMapper.selectByprojectDetailsNoAndRacetypesamsarano(projectDetailsItem.getProjectno(),raceTypeSamsaraIf.getRacetypesamsarano());
                    if(pif==null){
                        iff=1;
                        break;
                    }
                    if(pif.getExaminestatus()!=1){
                        iff=1;
                        break;
                    }
                }

                if(iff==0) {
                    listProjectDetailsVos.add(listProjectDetailsVo);
                }
                continue;
            }

            int iff = 0;
            //判断前面是否及格，是否要显示
            for(int i=1;i<listProjectDetailsVo.getRacetypedetailsstate();i++){
                RaceTypeSamsara raceTypeSamsaraIf = raceTypeSamsaraMapper.selectByRacetypenoAndRaceTypeSamsaraGrade(raceType.getRacetypeno(),i);
                if(raceTypeSamsaraIf==null){
                    iff=1;
                    break;
                }
                ProjectDetailsRaceTypeSamsara pif = projectDetailsRaceTypeSamsaraMapper.selectByprojectDetailsNoAndRacetypesamsarano(projectDetailsItem.getProjectno(),raceTypeSamsaraIf.getRacetypesamsarano());
                if(pif==null){
                    iff=1;
                    break;
                }
                if(pif.getExaminestatus()!=1){
                    iff=1;
                    break;
                }
            }

            if(iff==0) {
                listProjectDetailsVos.add(listProjectDetailsVo);
            }
        }

        return listProjectDetailsVos;
   }



    public static List<ProjectDetails> useLoop(List<ProjectDetails> projectDetailsList, List<ProjectDetailsUser> projectDetailsUserList){
        List<ProjectDetails> projectDetailsListRelth = new ArrayList<>();
        for(ProjectDetails projectDetailsListItem : projectDetailsList){

            for(ProjectDetailsUser projectDetailsUserListItem : projectDetailsUserList){
                if(projectDetailsListItem.getProjectno().equals(projectDetailsUserListItem.getProjectno())){
                    projectDetailsListRelth.add(projectDetailsListItem);
                }
            }

        }
        return projectDetailsListRelth;
    }


    public ServerResponse delete(List<Integer> projectnoList){
        if(CollectionUtils.isEmpty(projectnoList)){
            return ServerResponse.createByErrorMessage("未选择");
        }

        for(Integer projectnoItem : projectnoList){
            //需要软删除，所以改写
//            int rowCount = projectDetailsMapper.deleteByPrimaryKey(projectnoItem);
//            int rowCount2 = projectDetailsUserMapper.deleteByProjectNo(projectnoItem);
//            if(rowCount <= 0 || rowCount2 <= 0){
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return ServerResponse.createByErrorMessage("删除项目失败");
//            }
            ProjectDetails projectDetails = new ProjectDetails();
            projectDetails.setProjectno(projectnoItem);
            projectDetails.setIsvaild("2");
            int rowCount = projectDetailsMapper.updateByPrimaryKeySelective(projectDetails);
            if(rowCount <= 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ServerResponse.createByErrorMessage("删除项目失败");
            }
        }

        return ServerResponse.createBySuccessMessage("删除项目成功");
    }

    public ServerResponse Lock(List<Integer> projectnoList){
        if(CollectionUtils.isEmpty(projectnoList)){
            return ServerResponse.createByErrorMessage("未选择");
        }

        for(Integer projectnoItem : projectnoList){
            ProjectDetails projectDetails = new ProjectDetails();
            projectDetails.setIsvaild("1");
            projectDetails.setProjectno(projectnoItem);
            int rowCount = projectDetailsMapper.updateByPrimaryKeySelective(projectDetails);
            if(rowCount <= 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ServerResponse.createByErrorMessage("锁定项目失败");
            }
        }

        return ServerResponse.createBySuccessMessage("锁定项目成功");
    }

    public ServerResponse Deblock(List<Integer> projectnoList){
        if(CollectionUtils.isEmpty(projectnoList)){
            return ServerResponse.createByErrorMessage("未选择");
        }

        for(Integer projectnoItem : projectnoList){
            ProjectDetails projectDetails = new ProjectDetails();
            projectDetails.setIsvaild("0");
            projectDetails.setProjectno(projectnoItem);
            int rowCount = projectDetailsMapper.updateByPrimaryKeySelective(projectDetails);
            if(rowCount <= 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ServerResponse.createByErrorMessage("解锁项目失败");
            }
        }

        return ServerResponse.createBySuccessMessage("解锁项目成功");
    }

    public ServerResponse update(ProjectDetails projectDetails){

        if(projectDetails.getProjectno() == null && projectDetails.getProjectno() == 0){
            return ServerResponse.createByErrorMessage("没选中需要修改的用户");
        }

        int rowCount = projectDetailsMapper.updateByPrimaryKeySelective(projectDetails);
        if(rowCount > 0){
            return ServerResponse.createBySuccessMessage("更新项目成功");
        }
        return ServerResponse.createByErrorMessage("更新项目失败");
    }

    public ServerResponse setExcellentWorks(List<Integer> projectnoList){
        if(CollectionUtils.isEmpty(projectnoList)){
            return ServerResponse.createByErrorMessage("未选择");
        }

        for(Integer projectnoItem : projectnoList){

            ProjectDetails projectDetails = projectDetailsMapper.selectByPrimaryKey(projectnoItem);
            if(projectDetails==null){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ServerResponse.createByErrorMessage("添加优秀项目失败,项目不存在");
            }


            Integer excellentWorks = excellentWorksMapper.selectByProjectNoCount(projectnoItem);
            if(excellentWorks<=0){
                ExcellentWorks SetToexcellentWorksSetto = new ExcellentWorks();
                SetToexcellentWorksSetto.setProjectno(projectnoItem);
                int rowCount = excellentWorksMapper.insertSelective(SetToexcellentWorksSetto);
                if(rowCount <= 0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return ServerResponse.createByErrorMessage("添加优秀项目失败");
                }
            }
        }

        return ServerResponse.createBySuccessMessage("添加优秀项目成功");
    }

    public ServerResponse delExcellentWorks(List<Integer> projectnoList){
        if(CollectionUtils.isEmpty(projectnoList)){
            return ServerResponse.createByErrorMessage("未选择");
        }

        for(Integer projectnoItem : projectnoList){

            Integer excellentWorks = excellentWorksMapper.selectByProjectNoCount(projectnoItem);
            if(excellentWorks>0){
                int rowCount = excellentWorksMapper.deleteByProjectNo(projectnoItem);
                if(rowCount <= 0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return ServerResponse.createByErrorMessage("删除优秀项目失败");
                }
            }
        }

        return ServerResponse.createBySuccessMessage("删除优秀项目成功");
    }


    public ServerResponse getExcellentWorks(){



        List<Integer> list = excellentWorksMapper.seletAll();
        List<ExcellentWorksVo> excellentWorksVoList = new ArrayList<>();

        for(Integer Item : list){
            ProjectDetails projectDetails = projectDetailsMapper.selectByPrimaryKey(Item);
            if(projectDetails!=null){
                ExcellentWorksVo excellentWorksVo = new ExcellentWorksVo();
                excellentWorksVo.setProjectno(projectDetails.getProjectno());
                excellentWorksVo.setProjectname(projectDetails.getProjectname());
                excellentWorksVo.setCoverurl(projectDetails.getcoverurl());
                excellentWorksVo.setTeam(projectDetails.getTeam());
                excellentWorksVo.setProjectgrade(projectDetails.getProjectgrade());
                excellentWorksVo.setAddprojectstuname(projectDetails.getAddprojectstuname());
                excellentWorksVoList.add(excellentWorksVo);
            }
        }

        return ServerResponse.createBySuccess(excellentWorksVoList);
    }



    public ExportExcelVo<byte[]> exportBusInfo(List<Integer> projectnoList, HttpServletRequest request, HttpServletResponse response) throws Exception {

        ExportExcelVo<byte[]> exportExcelVo = null;

        ServerResponse<byte[]> rusult = null;

        String path = request.getSession().getServletContext().getRealPath("/") + File.separator + "WEB-INF" + File.separator + "file";
        //创建该文件对象
        File file_dir = new File(path);
        //如果保存文件的地址不存在，就先创建目录
        if (!file_dir.exists()) {
            file_dir.mkdir();
        }

        List<ProjectDetails> projectDetailsList;

        if(CollectionUtils.isEmpty(projectnoList)||projectnoList==null){
            projectDetailsList = projectDetailsMapper.selectByProjectAll();
        }else {
            projectDetailsList = projectDetailsMapper.selectByProjectnoList(projectnoList);
        }


        if (CollectionUtils.isEmpty(projectDetailsList)) {
            logger.info("未找到");
        }

        //得到项目信息列表
        List<ListProjectDetailsVo> listProjectDetailsVos = assembleProjectDetailsListVo(projectDetailsList);

        ExportExcel<ExcelProjectDetailsFileVo> extExcel = new ExportExcel<>();


        List<ExcelProjectDetailsFileVo> exList = new ArrayList<>();
        //表头
        String[] headers = {"项目ID", "项目名称", "申报状态","审核状态", "负责人", "项目级别","项目类型", "部门(学院)", "批次"};
        //sheet名称
        String sheetname = "项目信息";
        //路径+文件名
        String fileName = "项目信息" + System.currentTimeMillis() + ".xls";

        //创建该文件对象
        File file = new File(path, fileName);

        FileOutputStream out = null;

        try {
            out = new FileOutputStream(file);


            for (ListProjectDetailsVo listProjectDetailsVoItem : listProjectDetailsVos) {
                //如果不是整个user写入需要一个bean装换对象
                ExcelProjectDetailsFileVo excelFileVo = new ExcelProjectDetailsFileVo();
                excelFileVo.setProjectno(listProjectDetailsVoItem.getProjectno());
                excelFileVo.setProjectname(listProjectDetailsVoItem.getProjectname());
                excelFileVo.setIsvaild(listProjectDetailsVoItem.getIsvaild());
                if(listProjectDetailsVoItem.getExaminestatus()==0){
                    excelFileVo.setExaminestatus("未审核");
                }else if(listProjectDetailsVoItem.getExaminestatus()==1){
                    excelFileVo.setExaminestatus("通过");
                }else if(listProjectDetailsVoItem.getExaminestatus()==1){
                    excelFileVo.setExaminestatus("未通过");
                }
                excelFileVo.setStuinstitute(listProjectDetailsVoItem.getStuinstitute());
                excelFileVo.setProjectgrade(listProjectDetailsVoItem.getProjectgrade());
                excelFileVo.setProjecttype(listProjectDetailsVoItem.getProjecttype());
                excelFileVo.setInstructor(listProjectDetailsVoItem.getInstructor());
                excelFileVo.setRacetypedetailsstate(listProjectDetailsVoItem.getRacetypedetailsstate());
                exList.add(excelFileVo);
            }
            //生产excel文件
            extExcel.exportExcelCar(headers, sheetname, exList, out);

            rusult = extExcel.download(path, fileName, request, response);
            System.out.println("rusult="+rusult.getData());


        } catch (Exception e) {
            exportExcelVo.setFileName(null);
            exportExcelVo.setServerResponse(ServerResponse.createByErrorMessage("异常退出"));
            return exportExcelVo;
        } finally {
            out.close();
            File file1 = new File(path, fileName);
            file1.delete();

        }
        if (rusult != null){
//            Gson gson = new Gson();
//            String r;
//            r = gson.toJson(ServerResponse.createBySuccess(rusult));
            fileName = ExportExcel.getFilename(request,fileName);
            exportExcelVo = new ExportExcelVo<>();
            exportExcelVo.setFileName(fileName);
            exportExcelVo.setServerResponse(rusult);
            return exportExcelVo;
        }
        else
        {
            exportExcelVo.setFileName(null);
            exportExcelVo.setServerResponse(ServerResponse.createByErrorMessage("没有文件导出"));
            return exportExcelVo;
        }
    }

    DecimalFormat df2 =new DecimalFormat("#");

    /**
     * 比赛结果
     * @param pageNum
     * @param pageSize
     * @param racetypesamsarano
     * @param weightFrom
     * @return
     */
    public ServerResponse listProductResult(int pageNum, int pageSize,Integer racetypesamsarano,Integer weightFrom){

        RaceTypeSamsara raceTypeSamsara = raceTypeSamsaraMapper.selectByPrimaryKey(racetypesamsarano);
        if(raceTypeSamsara==null){
            return ServerResponse.createByErrorMessage("没有该项目轮次");
        }

        RaceType raceType = raceTypeMapper.selectByPrimaryKey(raceTypeSamsara.getRacetypeno());
        if(raceType==null){
            return ServerResponse.createByErrorMessage("没有该比赛类型");
        }
        RaceTypeDetails raceTypeDetails = raceTypeDetailsMapper.selectByRacetypeno(raceType.getRacetypeno());
        if(raceTypeDetails==null){
            return ServerResponse.createByErrorMessage("比赛没开始");

        }

        if(raceTypeDetails.getRacetypedetailsstate() < raceTypeSamsara.getRacetypesamsaragrade()&&raceTypeDetails.getRacetypedetailsstate()!=-1){
            return ServerResponse.createByErrorMessage("比赛该轮次没开始");
        }
        if(raceTypeDetails.getRacetypedetailsstate() == raceTypeSamsara.getRacetypesamsaragrade()){
            return ServerResponse.createByErrorMessage("比赛该轮次没结束");
        }


        RaceTypeSamsara raceTypeSamsara2 = new RaceTypeSamsara();
        raceTypeSamsara2.setRacetypesamsarano(racetypesamsarano);
        raceTypeSamsara2.setWeight(weightFrom);
        int rsrsult = raceTypeSamsaraMapper.updateByPrimaryKeySelective(raceTypeSamsara2);
        if(rsrsult<=0){
            return ServerResponse.createByErrorMessage("插入失败");
        }



//        //这个学院所有成员
//        List<Integer> stuList = userMapper.selectInstitute(stuInstitute);
//        //这个学院人员的项目联系id
//        List<ProjectDetailsUser> projectDetailsUserList = projectDetailsUserMapper.selecttProjectstunoList(stuList);
//        //与这个
//        List<ProjectDetailsRaceTypeSamsara> projectDetailsRaceTypeSamsaraList = projectDetailsRaceTypeSamsaraMapper.selectByRacetypesamsarano(racetypesamsarano);
//        //所有符合的项目id
//        List<Integer> list = new ArrayList<>();
//        for(ProjectDetailsRaceTypeSamsara Item1:projectDetailsRaceTypeSamsaraList){
//            for(ProjectDetailsUser Item2:projectDetailsUserList){
//                if(Item1.getProjectdetailsno()==Item2.getProjectno()){
//                    list.add(Item1.getProjectdetailsno());
//                }
//            }
//        }
//        //所有符合的项目.出错
//        List<ProjectDetails> projectDetailsList = projectDetailsMapper.selectByProjectnoList(list);
        List<ProjectDetailsRaceTypeSamsara> projectDetailsRaceTypeSamsaraList = projectDetailsRaceTypeSamsaraMapper.selectByRacetypesamsarano(racetypesamsarano);

        List<ProjectDetailsResultVo> list = new ArrayList<>();

        for(ProjectDetailsRaceTypeSamsara Item3 : projectDetailsRaceTypeSamsaraList) {
            ProjectDetails projectDetails = projectDetailsMapper.selectByPrimaryKey(Item3.getProjectdetailsno());
            if(projectDetails==null){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ServerResponse.createByErrorMessage("部分项目找不到");
            }
            ProjectDetailsResultVo projectDetailsResultVo = new ProjectDetailsResultVo();
            projectDetailsResultVo.setProjectno(projectDetails.getProjectno());
            projectDetailsResultVo.setProjectname(projectDetails.getProjectname());
            projectDetailsResultVo.setInstructor(projectDetails.getInstructor());
            projectDetailsResultVo.setProjectgrade(projectDetails.getProjectgrade());
            projectDetailsResultVo.setProjecttype(projectDetails.getProjecttype());
            ProjectDetailsUser projectDetailsUser = projectDetailsUserMapper.selectByProjectno(projectDetails.getProjectno());
            User user = userMapper.selectByPrimaryKey(projectDetailsUser.getStuno());
            if(user==null){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ServerResponse.createByErrorMessage("部分项目的用户找不到");
            }
            projectDetailsResultVo.setStuInstitute(user.getStuinstitute());
            int ballot = Item3.getBallot();
            String reviewnotes = Item3.getReviewnotes();

            Integer reviewnotesInt;
            if(reviewnotes==null){
                reviewnotesInt=0;
            }else {
                reviewnotesInt = Integer.valueOf(reviewnotes.trim());
            }
            projectDetailsResultVo.setBallot(ballot);
            projectDetailsResultVo.setReviewnotes(reviewnotesInt);
            Integer aggscore;
            float reviewnotesfloat=reviewnotesInt;
            float ballotfloat=ballot;
            aggscore= Integer.parseInt(df2.format((reviewnotesfloat*weightFrom/100)+(ballotfloat*(100-weightFrom)/100)));
            projectDetailsResultVo.setAggregateScore(aggscore);
            list.add(projectDetailsResultVo);
        }
        //排序
        Collections.sort(list);
        int pages = (int)(list.size()/pageSize);
        if(list.size()%pageSize!=0){
            pages+=1;
        }
        if(pageNum>pages){
            return ServerResponse.createBySuccessMessage("项目为空");
        }
        Map<String,Object> map = new HashMap<>();

        if(list.size()%pageSize!=0){
            if(pages==pageNum){
                map.put("list",list.subList((pageNum-1)*pageSize,list.size()));
            }else {
                map.put("list",list.subList((pageNum-1)*pageSize,pageNum*pageSize));
            }
        } else {
            map.put("list",list.subList((pageNum-1)*pageSize,pageNum*pageSize));
        }
        map.put("pages",pages);
        map.put("pageNum",pageNum);
        map.put("pageSize",pageSize);
        map.put("pageTotal",list.size());


        return ServerResponse.createBySuccess("返回结果项目列表成功",map);
    }

    /**
     * 比赛结果-导出
     * @param racetypesamsarano
     * @param weightFrom
     * @return
     */
    public ExportExcelVo<byte[]> listProductResultInfor(Integer racetypesamsarano,Integer weightFrom, HttpServletRequest request, HttpServletResponse response)throws Exception{

        ExportExcelVo<byte[]> exportExcelVo=null;

        RaceTypeSamsara raceTypeSamsara = raceTypeSamsaraMapper.selectByPrimaryKey(racetypesamsarano);
        if(raceTypeSamsara==null){
            exportExcelVo.setFileName(null);
            exportExcelVo.setServerResponse(ServerResponse.createByErrorMessage("没有文件导出"));
            return exportExcelVo;
        }

        RaceType raceType = raceTypeMapper.selectByPrimaryKey(raceTypeSamsara.getRacetypeno());
        if(raceType==null){
            exportExcelVo.setFileName(null);
            exportExcelVo.setServerResponse(ServerResponse.createByErrorMessage("没有文件导出"));
            return exportExcelVo;
        }
        RaceTypeDetails raceTypeDetails = raceTypeDetailsMapper.selectByRacetypeno(raceType.getRacetypeno());
        if(raceTypeDetails==null){
            exportExcelVo.setFileName(null);
            exportExcelVo.setServerResponse(ServerResponse.createByErrorMessage("没有文件导出"));
            return exportExcelVo;

        }

        if(raceTypeDetails.getRacetypedetailsstate() < raceTypeSamsara.getRacetypesamsaragrade()&&raceTypeDetails.getRacetypedetailsstate()!=-1){
            exportExcelVo.setFileName(null);
            exportExcelVo.setServerResponse(ServerResponse.createByErrorMessage("没有文件导出"));
            return exportExcelVo;
        }
        if(raceTypeDetails.getRacetypedetailsstate() == raceTypeSamsara.getRacetypesamsaragrade()){
            exportExcelVo.setFileName(null);
            exportExcelVo.setServerResponse(ServerResponse.createByErrorMessage("没有文件导出"));
            return exportExcelVo;
        }

        RaceTypeSamsara raceTypeSamsara2 = new RaceTypeSamsara();
        raceTypeSamsara2.setRacetypesamsarano(racetypesamsarano);
        raceTypeSamsara2.setWeight(weightFrom);
        int rsrsult = raceTypeSamsaraMapper.updateByPrimaryKeySelective(raceTypeSamsara2);
        if(rsrsult<=0){
            exportExcelVo.setFileName(null);
            exportExcelVo.setServerResponse(ServerResponse.createByErrorMessage("没有文件导出"));
            return exportExcelVo;
        }

        List<ProjectDetailsRaceTypeSamsara> projectDetailsRaceTypeSamsaraList = projectDetailsRaceTypeSamsaraMapper.selectByRacetypesamsarano(racetypesamsarano);

        List<ProjectDetailsResultVo> list = new ArrayList<>();

        for(ProjectDetailsRaceTypeSamsara Item3 : projectDetailsRaceTypeSamsaraList) {
            ProjectDetails projectDetails = projectDetailsMapper.selectByPrimaryKey(Item3.getProjectdetailsno());
            if(projectDetails==null){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                exportExcelVo.setFileName(null);
                exportExcelVo.setServerResponse(ServerResponse.createByErrorMessage("没有文件导出"));
                return exportExcelVo;
            }
            ProjectDetailsResultVo projectDetailsResultVo = new ProjectDetailsResultVo();
            projectDetailsResultVo.setProjectno(projectDetails.getProjectno());
            projectDetailsResultVo.setProjectname(projectDetails.getProjectname());
            projectDetailsResultVo.setInstructor(projectDetails.getInstructor());
            projectDetailsResultVo.setProjectgrade(projectDetails.getProjectgrade());
            projectDetailsResultVo.setProjecttype(projectDetails.getProjecttype());
            ProjectDetailsUser projectDetailsUser = projectDetailsUserMapper.selectByProjectno(projectDetails.getProjectno());
            User user = userMapper.selectByPrimaryKey(projectDetailsUser.getStuno());
            if(user==null){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                exportExcelVo.setFileName(null);
                exportExcelVo.setServerResponse(ServerResponse.createByErrorMessage("没有文件导出"));
                return exportExcelVo;
            }
            projectDetailsResultVo.setStuInstitute(user.getStuinstitute());
            int ballot = Item3.getBallot();
            String reviewnotes = Item3.getReviewnotes();

            Integer reviewnotesInt;
            if(reviewnotes==null){
                reviewnotesInt=0;
            }else {
                reviewnotesInt = Integer.valueOf(reviewnotes.trim());
            }
            projectDetailsResultVo.setBallot(ballot);
            projectDetailsResultVo.setReviewnotes(reviewnotesInt);
            Integer aggscore;
            float reviewnotesfloat=reviewnotesInt;
            float ballotfloat=ballot;
            aggscore= Integer.parseInt(df2.format((reviewnotesfloat*weightFrom/100)+(ballotfloat*(100-weightFrom)/100)));
            projectDetailsResultVo.setAggregateScore(aggscore);
            list.add(projectDetailsResultVo);
        }
        //排序
        Collections.sort(list);


        ServerResponse<byte[]> rusult = null;

        String path = request.getSession().getServletContext().getRealPath("/") + File.separator + "WEB-INF" + File.separator + "file";
        //创建该文件对象
        File file_dir = new File(path);
        //如果保存文件的地址不存在，就先创建目录
        if (!file_dir.exists()) {
            file_dir.mkdir();
        }








        ExportExcel<ProjectDetailsResultVo> extExcel = new ExportExcel<>();


        //表头
        String[] headers = {"项目ID", "项目名称", "负责人", "项目级别","项目类型", "部门(学院)","评委平均分","投票得分","总分"};
        //sheet名称
        String sheetname = "比赛结果信息";
        //路径+文件名
        String fileName = "比赛结果信息" + System.currentTimeMillis() + ".xls";

        //创建该文件对象
        File file = new File(path, fileName);

        FileOutputStream out = null;

        try {
            out = new FileOutputStream(file);

            //生产excel文件
            extExcel.exportExcelCar(headers, sheetname, list, out);

            rusult = extExcel.download(path, fileName, request, response);


        } catch (Exception e) {
            exportExcelVo.setFileName(null);
            exportExcelVo.setServerResponse(ServerResponse.createByErrorMessage("异常退出"));
            return exportExcelVo;
        } finally {
            out.close();
            File file1 = new File(path, fileName);
            file1.delete();

        }
        if (rusult != null){
//            Gson gson = new Gson();
//            String r;
//            r = gson.toJson(ServerResponse.createBySuccess(rusult));
            fileName = ExportExcel.getFilename(request,fileName);
            exportExcelVo = new ExportExcelVo<>();
            exportExcelVo.setFileName(fileName);
            exportExcelVo.setServerResponse(rusult);
            return exportExcelVo;
        }
        else
        {
            exportExcelVo.setFileName(null);
            exportExcelVo.setServerResponse(ServerResponse.createByErrorMessage("没有文件导出"));
            return exportExcelVo;
        }


    }

}
